package com.commerce.order.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.commerce.common.utils.PageResult;
import com.commerce.common.entity.Order;
import com.commerce.common.entity.OrderItem;
import com.commerce.common.entity.Product;

import com.commerce.common.exception.BusinessException;
import com.commerce.order.mapper.OrderMapper;
import com.commerce.order.service.OrderItemService;
import com.commerce.order.service.OrderService;



import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.commerce.product.service.ProductService;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;

@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements OrderService {

    @Autowired
    private OrderItemService orderItemService;

    @Autowired
    private ProductService productService;

    @Autowired(required = false)
    private com.commerce.order.feign.AddressFeignClient addressFeignClient;
    


    /**
     * 创建订单
     */
    @Override
    @Transactional
    public Order createOrder(Order order) {
        // 生成订单号
        order.setOrderNo(generateOrderNo());
        // 设置订单状态为待支付
        order.setStatus(1);
        // 设置实付金额（初始为订单总金额）
        if (order.getPayAmount() == null) {
            order.setPayAmount(order.getTotalAmount());
        }
        // 设置运费金额
        if (order.getFreightAmount() == null) {
            order.setFreightAmount(0.0);
        }
        // 设置折扣金额
        if (order.getDiscountAmount() == null) {
            order.setDiscountAmount(0.0);
        }
        // 设置收货人信息
        if (order.getAddressId() != null) {
            try {
                if (addressFeignClient != null) {
                    com.commerce.common.utils.Result<com.commerce.common.entity.Addresses> addressResult =
                        addressFeignClient.getAddressById(order.getAddressId());
                    if (addressResult != null && addressResult.isSuccess() && addressResult.getData() != null) {
                        com.commerce.common.entity.Addresses address = addressResult.getData();
                        order.setReceiverName(address.getName());
                        order.setReceiverPhone(address.getPhone());
                        order.setReceiverAddress(address.getProvince() + " " + address.getCity() + " " +
                                               address.getDistrict() + " " + address.getDetailAddress());
                    }
                }
            } catch (Exception e) {
                log.warn("获取地址信息失败，使用默认值: {}", e.getMessage());
            }
        }

        // 如果没有设置收货人信息，使用默认值
        if (order.getReceiverName() == null || order.getReceiverName().isEmpty()) {
            order.setReceiverName("未知收货人");
        }
        if (order.getReceiverPhone() == null || order.getReceiverPhone().isEmpty()) {
            order.setReceiverPhone("未知电话");
        }
        if (order.getReceiverAddress() == null || order.getReceiverAddress().isEmpty()) {
            order.setReceiverAddress("未知地址");
        }

        // 设置创建时间
        order.setCreateTime(LocalDateTime.now());

        // 保存订单
        save(order);
        
        // 保存订单项
        if (order.getOrderItems() != null && !order.getOrderItems().isEmpty()) {
            log.info("开始保存订单项，订单ID: {}, 订单项数量: {}", order.getId(), order.getOrderItems().size());

            for (OrderItem item : order.getOrderItems()) {
                try {
                    // 设置订单ID
                    item.setOrderId(order.getId());
                    // 设置创建时间
                    item.setCreateTime(LocalDateTime.now());

                    log.info("处理订单项，商品ID: {}, 数量: {}", item.getProductId(), item.getQuantity());

                    // 获取商品信息
                    Product product = productService.getProductById(item.getProductId());
                    if (product == null) {
                        log.error("商品不存在，商品ID: {}", item.getProductId());
                        throw new BusinessException("商品不存在");
                    }

                    log.info("获取到商品信息: {}, 价格: {}, 库存: {}", product.getName(), product.getPrice(), product.getStock());

                    // 设置商品信息
                    item.setProductName(product.getName());
                    item.setProductImage(product.getMainImage());
                    item.setPrice(product.getPrice().doubleValue());
                    item.setTotalPrice(product.getPrice().doubleValue() * item.getQuantity());

                    // 保存订单项
                    log.info("保存订单项: {}", item);
                    boolean saveResult = orderItemService.save(item);
                    log.info("订单项保存结果: {}, 订单项ID: {}", saveResult, item.getId());

                    if (!saveResult) {
                        log.error("订单项保存失败");
                        throw new BusinessException("订单项保存失败");
                    }

                    // 减少商品库存
                    product.setStock(product.getStock() - item.getQuantity());
                    productService.updateById(product);
                    log.info("更新商品库存成功，商品ID: {}, 剩余库存: {}", product.getId(), product.getStock());

                } catch (Exception e) {
                    log.error("保存订单项失败，商品ID: {}, 错误信息: {}", item.getProductId(), e.getMessage(), e);
                    throw new BusinessException("保存订单项失败: " + e.getMessage());
                }
            }

            log.info("所有订单项保存完成");
        }
        
        return getOrderDetail(order.getId());
    }

    /**
     * 获取订单分页列表
     */
    @Override
    public PageResult<Order> getPageList(int page, int size, Long userId, Integer status, String orderNo) {
        // 创建分页对象
        Page<Order> pageParam = new Page<>(page, size);
        
        // 构建查询条件
        LambdaQueryWrapper<Order> queryWrapper = new LambdaQueryWrapper<>();
        
        // 添加查询条件
        if (userId != null) {
            queryWrapper.eq(Order::getUserId, userId);
        }
        
        if (status != null) {
            queryWrapper.eq(Order::getStatus, status);
        }
        
        if (StringUtils.hasText(orderNo)) {
            queryWrapper.like(Order::getOrderNo, orderNo);
        }
        
        // 按创建时间降序排序
        queryWrapper.orderByDesc(Order::getCreateTime);
        
        // 执行分页查询
        Page<Order> resultPage = page(pageParam, queryWrapper);
        
        // 查询订单项
        resultPage.getRecords().forEach(this::fillOrderItems);
        
        // 返回分页结果
        return new PageResult<>(resultPage.getTotal(), resultPage.getRecords());
    }

    /**
     * 获取订单详情
     */
    @Override
    public Order getOrderDetail(Long id) {
        // 获取订单
        Order order = getById(id);
        if (order == null) {
            return null;
        }
        
        // 填充订单项
        fillOrderItems(order);
        
        return order;
    }

    /**
     * 更新订单状态
     */
    @Override
    @Transactional
    public Order updateOrderStatus(Long id, Integer status) {
        // 获取订单
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 更新状态
        order.setStatus(status);
        order.setUpdateTime(LocalDateTime.now());
        updateById(order);
        
        return getOrderDetail(id);
    }

    /**
     * 取消订单
     */
    @Override
    @Transactional
    public Order cancelOrder(Long id) {
        // 获取订单
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 检查订单状态
        if (order.getStatus() != 1) {
            throw new BusinessException("只有待支付订单可以取消");
        }
        
        // 更新状态为已取消
        order.setStatus(0);
        order.setUpdateTime(LocalDateTime.now());
        updateById(order);
        
        // 恢复商品库存
        fillOrderItems(order);
        for (OrderItem item : order.getOrderItems()) {
            Product product = productService.getProductById(item.getProductId());
            if (product != null) {
                product.setStock(product.getStock() + item.getQuantity());
                productService.updateById(product);
            }
        }
        
        return order;
    }

    /**
     * 支付订单
     */
    @Override
    @Transactional
    public Order payOrder(Long id) {
        // 获取订单
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 检查订单状态
        if (order.getStatus() != 1) {
            throw new BusinessException("只有待支付订单可以支付");
        }
        
        // 更新状态为已支付
        order.setStatus(2);
        order.setPaymentTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        updateById(order);
        
        return getOrderDetail(id);
    }

    /**
     * 确认收货
     */
    @Override
    @Transactional
    public Order confirmReceive(Long id) {
        // 获取订单
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }
        
        // 检查订单状态
        if (order.getStatus() != 3) {
            throw new BusinessException("只有已发货订单可以确认收货");
        }
        
        // 更新状态为已完成
        order.setStatus(4);
        order.setReceiveTime(LocalDateTime.now());
        order.setUpdateTime(LocalDateTime.now());
        updateById(order);
        
        return getOrderDetail(id);
    }

    /**
     * 获取用户订单列表
     */
    @Override
    public PageResult<Order> getUserOrders(Long userId, int page, int size, Integer status) {
        return getPageList(page, size, userId, status, null);
    }

    /**
     * 申请退款
     */
    @Override
    @Transactional
    public Order refundOrder(Long id) {
        // 获取订单
        Order order = getById(id);
        if (order == null) {
            throw new BusinessException("订单不存在");
        }

        // 检查订单状态
        if (order.getStatus() != 2 && order.getStatus() != 3 && order.getStatus() != 4) {
            throw new BusinessException("只有已支付、已发货或已完成的订单可以申请退款");
        }

        // 更新状态为退款中
        order.setStatus(5);
        order.setUpdateTime(LocalDateTime.now());
        updateById(order);

        // 这里可以添加退款处理逻辑，比如调用支付平台的退款API
        // 目前是模拟退款，直接标记为退款中状态

        return getOrderDetail(id);
    }
    
    /**
     * 填充订单项
     */
    private void fillOrderItems(Order order) {
        LambdaQueryWrapper<OrderItem> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(OrderItem::getOrderId, order.getId());
        List<OrderItem> orderItems = orderItemService.list(queryWrapper);
        order.setOrderItems(orderItems);
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        // 生成基于时间戳和随机数的订单号
        return System.currentTimeMillis() + UUID.randomUUID().toString().substring(0, 8);
    }


}